<template>
    <TableView class="table">
        <template #form>
            <NSpace justify="space-between">
                <NSpace align="center">
                    <div>
                        资产编号:
                        <NInput style="width: 200rem" placeholder="请输入资产编号" v-model:value="paginationReactive.assetNumber"
                            clearable />
                    </div>
                    <div v-if="!isFromAssetsItem">
                        资产名称:
                        <NInput style="width: 200rem" placeholder="请输入资产名称" v-model:value="paginationReactive.assetName"
                            clearable />
                    </div>
                    <div>
                        旧资产编号:
                        <NInput style="width: 200rem" placeholder="请输入旧资产编号" v-model:value="paginationReactive.oldAssetNumber"
                            clearable />
                    </div>
                    <div class="center">
                        资产类目：
                        <NTreeSelect style="width: 200rem" :options="categoryList"
                            v-model:value="paginationReactive.categoriesId" clearable label-field="categoriesName"
                            key-field="id" children-field="childList" />
                    </div>
                    <div class="center">
                        存放位置：
                        <NTreeSelect style="width: 200rem" :options="warehouseList"
                            v-model:value="paginationReactive.warehouseId" clearable label-field="warehouseName" 
                            key-field="id" children-field="childList" />
                    </div>
                    <div class="center">
                        状态：
                        <NSelect style="width: 180rem" :options="statusOptions" v-model:value="paginationReactive.status"
                            clearable />
                    </div>
                    <NButton type="primary" ghost @click="search">
                        查找
                    </NButton>
                    <NButton type="primary" @click="exportData" :loading="exportLoading">
                        导出
                    </NButton>
                    <NButton type="primary" @click="createQRCode">
                        生成二维码
                    </NButton>
                    <NButton type="primary" style="width: 115rem"
                        @click="$router.push({ path: '/OA/Assets/AssetAdd' })">
                        资产新增
                    </NButton>
                    <NButton type="primary" style="width: 115rem"
                        @click="$router.push({ path: '/OA/Assets/AssetImport' })">
                        资产导入
                    </NButton>
                </NSpace>
            </NSpace>
        </template>

        <template #table="props">
            <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
                :loading="tableLoading" :row-key="(row) => row.id" @update:checked-row-keys="handleDataCheck" />
        </template>

        <template #pagination>
            <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
                show-size-picker show-quick-jumper :suffix="() => '页'">
                <template #prefix>
                    <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </template>
    </TableView>
</template>
<script setup lang="ts">
import { NSpace, NButton, NDataTable, NPagination, useMessage, NModal, NInput, NTreeSelect, NSelect } from 'naive-ui'
import { h, reactive, ref, watch, onDeactivated, onMounted, defineProps } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DataTableColumns, DataTableRowKey } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import type { HttpResponse } from '@/utils/http'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()

// const props = defineProps({
//     id: { type: [Number, String], default: () => null, required: false }
// })

const statusOptions = [
    { value: -1, label: '全部' },
    { value: 0, label: '在库' },
    { value: 1, label: '使用中' },
    { value: 2, label: '停用' },
]
const exportLoading = ref<boolean>(false)
// 导出
const exportData = async () => {
    exportLoading.value = true
    let params: any = {}
    if (checkedRowKeys.value.length > 0) {
        params = { exportIds: checkedRowKeys.value.map(v => Number(v)) }
    } else {
        params = {
            page: paginationReactive.page,
            limit: paginationReactive.pageSize,
            // assetName: paginationReactive.assetName, // 资产名称
            categoriesId: getAllChildList(categoryList.value, paginationReactive.categoriesId), // 资产类目
            warehouseIds: getAllChildList(warehouseList.value, paginationReactive.warehouseId), // 存放位置
            assetNumber: paginationReactive.assetNumber, // 资产编号
            oldAssetNumber: paginationReactive.oldAssetNumber, // 资产编号
            status: (paginationReactive.status !== -1) ? paginationReactive.status : null // 资产状态
        }
        if (isFromAssetsItem.value) {
            params.assetName = paginationReactive.assetName
        } else {
            params.assetNameLike = paginationReactive.assetName
        }
    }
    const [error, res, headers] = await sendRequest({
        module: 'assetsManagement',
        api: 'exportAssetInfo',
        override: {
            data: {
                ...params
            }
        }
    })
    if (error) {
        exportLoading.value = false
        return message.error(error.message)
    }
    download(headers, res, '资产详情')
    message.success('导出成功')
    exportLoading.value = false
}
function download(headers: any, data: any, name?: string) {
    const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
    let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
    if (!filename.includes('xlsx')) {
        filename = filename.replace('xls', 'xlsx')
    }
    const a = document.createElement('a')
    let binaryData = []
    binaryData.push(data)
    a.href = window.URL.createObjectURL(new Blob(binaryData))
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(a.href)
}
/** 生成二维码 */
const createQRCode = () => {
    if (!(checkedRowKeys.value.length > 0)) {
        return message.warning("请至少选择一条数据")
    }
    // 存储临时数据
    const newList = tableData.value.filter((t: any) => {
        return checkedRowKeys.value.includes(t.id)
    })
    localStorage.setItem("hzbbg-assets-data", JSON.stringify(newList))
    router.push({ path: '/OA/Assets/QRCdoe' })
}
const checkedRowKeys = ref<DataTableRowKey[]>([])
const handleDataCheck = (rowKeys: DataTableRowKey[]) => {
    checkedRowKeys.value = rowKeys
}

const columns: DataTableColumns = [
    {
        type: 'selection',
    },
    {
        title: '资产编号',
        key: 'assetNumber',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '资产名称',
        key: 'assetName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '资产类目',
        key: 'categoriesName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '使用人',
        key: 'userName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '存放位置',
        key: 'warehouseName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '状态',
        key: 'statusValue',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '可否领用',
        key: 'requisitionFlagValue',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '旧资产编码',
        key: 'oldAssetNumber',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '操作',
        key: 'action',
        align: useStore.isCenter,
        width: 120,
        fixed: 'right',
        render: (row: any) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: async () => {
                        router.push({ path: '/OA/Assets/AssetsDetailEdit', query: { id: row.id } })
                    }
                },
                {
                    default: () => '编辑'
                }
            ),
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: async () => router.push({ path: '/OA/Assets/AssetsLog', query: { id: row.id } })
                },
                {
                    default: () => '日志'
                }
            )
        ]
    }
]
// 上一页下一页
const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    assetNumber: null, // 资产编号
    oldAssetNumber: null, // 旧资产编号
    assetName: null, // 资产名称
    categoriesId: null, // 资产类目
    warehouseId: null, // 存放位置
    status: null, // 状态
    onChange: (page: number) => {
        paginationReactive.page = page
        getAssetsList()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        getAssetsList()
    }
})
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
// 点击查找
const search = () => {
    paginationReactive.page = 1
    getAssetsList()
}
const getAssetsList = async () => {
    tableLoading.value = true
    let params: any = {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        // assetName: paginationReactive.assetName, // 资产名称
        categoriesId: getAllChildList(categoryList.value, paginationReactive.categoriesId), // 资产类目
        warehouseIds: getAllChildList(warehouseList.value, paginationReactive.warehouseId), // 存放位置
        assetNumber: paginationReactive.assetNumber, // 资产编号
        oldAssetNumber: paginationReactive.oldAssetNumber, // 资产编号
        status: (paginationReactive.status !== -1) ? paginationReactive.status : null // 资产状态
    }
    if (isFromAssetsItem.value) {
        params.assetName = paginationReactive.assetName
    } else {
        params.assetNameLike = paginationReactive.assetName
    }
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getAssetInfoList',
        override: {
            data: {
                ...params
            }
        }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    tableData.value = []
    setTimeout(() => {
        tableData.value = res.data.list
        paginationReactive.itemCount = res.data.totalCount
    }, 0)
}

const keyUpDown = (e: any) => e.key == 'Enter' && getAssetsList()

onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

/** 获取资产详情（拿到类目和name） */
const getAssetsDetail = async (id: number) => {
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getAssetInfo',
        uri: {
            id
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    return res.data
}
const categoryList = ref<any>([])
/** 获取类目下拉 */
const getCategoryList = async () => {
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'getCategoryList',
        override: {
            data: {}
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    categoryList.value = res.data
}
const isFromAssetsItem = ref<boolean>(false)

const warehouseList = ref<any>([])
/** 获取位置下拉 */
const getWarehouseList = async () => {
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'getWarehouseList',
        override: {
            data: {}
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    warehouseList.value = res.data
}
onMounted(async () => {
    await getCategoryList();
    await getWarehouseList();
    // if(name) {
    // const { assetName, categoriesId } = await getAssetsDetail(Number(id))
    // paginationReactive.categoriesId = categoriesId
    // paginationReactive.assetName = assetName

    // }
    // getAssetsList()
    window.addEventListener('keyup', keyUpDown, false)  // 回车
})

/**选择节点返回所有子节点id */
const getAllChildList = (data, val) => {
  if (!val) return val
  console.log('val: ', val)
  function getObjById(list, id) {
    if (!list instanceof Array) {
      return null
    }

    for (let i in list) {
      let item = list[i]
      if (item.id === id) {
        return item
      } else {
        if (item.childList) {
          let value = getObjById(item.childList, id)
          if (value) {
            return value
          }
        }
      }
    }
  }
  function getChildren(list, returnValue = [val]) {
    for (let i in list) {
      returnValue.push(list[i].id)
      if (list[i].childList) {
        getChildren(list[i].childList, returnValue)
      }
    }
    return returnValue
  }
  let obj = getObjById(data, val)
  if (obj && obj.childList) {
    let childrenList = getChildren(obj.childList)
    return childrenList
  } else return [val]
}

watch(
    () => route,
    async () => {
        const { name } = route.query
        if (name) {
            isFromAssetsItem.value = true
            paginationReactive.assetName = (name as any)
        } else {
            isFromAssetsItem.value = false
            paginationReactive.assetName = null
        }
        if (route.path == '/OA/Assets/AssetsDetail') {
            getAssetsList()
        }
    },
    { deep: true, immediate: true }
)

</script>
<style scoped lang="scss">
.table {
    padding: 29rem 30rem 42rem;
}
.center {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>